package com.ruoyi.web.controller.project;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ProjectUser;
import com.ruoyi.system.domain.vo.ProjectPurchaseMaterialNumVO;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Project;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 项目Controller
 * 
 * @author ruoyi
 * @date 2025-03-11
 */
@RestController
@RequestMapping("/project")
@RequiredArgsConstructor
@Api(tags = "项目")
public class ProjectController extends BaseController{

    private final IProjectService projectService;

    private final IProjectUserService projectUserService;

    private final IProjectPurchaseMaterialService projectPurchaseMaterialService;

    private final IProjectPurchaseService projectPurchaseService;

    private final IProjectPurchaseOrderService projectPurchaseOrderService;

    @GetMapping("/list")
    @ApiOperation("查询项目列表")
    public TableDataInfo list(@RequestParam(value = "name",required = false)String name,
                              @RequestParam(value = "userId",required = false)Long userId)
    {
        startPage();
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.eq("delete_tag",0);
        if (StringUtils.isNotEmpty(name)){
            wrapper.like("name",name);
        }
        if (userId != null){
            QueryWrapper<ProjectUser> projectUserQueryWrapper = new QueryWrapper<>();
            projectUserQueryWrapper.eq("user_id",userId);
            List<ProjectUser> list = projectUserService.list(projectUserQueryWrapper);
            if (list != null && list.size()>0){
                wrapper.in("id",list.stream().map(ProjectUser::getProjectId).collect(Collectors.toList()));
            }else {
                return getDataTable(new ArrayList<>());
            }
        }
        wrapper.orderByDesc("created_time");
        List<Project> list = projectService.list(wrapper);
        return getDataTable(list);
    }



    @GetMapping(value = "/{id}")
    @ApiOperation("获取项目详细信息")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(projectService.getById(id));
    }


    @Log(title = "项目", businessType = BusinessType.INSERT)
    @ApiOperation("新增项目")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Project project)
    {
        project.setDeleteTag(0);
        project.setCreatedTime(new Date());
        boolean save = projectService.save(project);
//        saveUser(project);
        return toAjax(save);
    }


    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @ApiOperation("修改项目")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody Project project)
    {
        boolean result = projectService.updateById(project);
        saveUser(project);
        return toAjax(result);
    }

    private void saveUser(Project project){
        QueryWrapper<ProjectUser> projectUserQueryWrapper = new QueryWrapper<>();
        projectUserQueryWrapper.eq("project_id",project.getId());
        projectUserService.remove(projectUserQueryWrapper);
        project.getUserIdList().forEach(m->{
            ProjectUser projectUser = new ProjectUser();
            projectUser.setProjectId(project.getId());
            projectUser.setUserId(m);
            projectUserService.save(projectUser);
        });
    }

    @Log(title = "项目", businessType = BusinessType.DELETE)
    @ApiOperation("删除项目")
	@PostMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        UpdateWrapper<Project> wrapper = new UpdateWrapper<>();
        wrapper.set("delete_tag",1);
        wrapper.in("id",ids);
        return toAjax(projectService.update(wrapper));
    }

    @GetMapping("/getNum")
    public AjaxResult getNum(){
        ProjectPurchaseMaterialNumVO totalByMonth = projectPurchaseMaterialService.getTotalByMonth(new SimpleDateFormat("yyyy-MM").format(new Date()),null);
        return AjaxResult.success(totalByMonth);
    }

    @GetMapping("/getChat")
    public AjaxResult getChat(){
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("purchase",projectPurchaseService.getChat());
        ajaxResult.put("order",projectPurchaseOrderService.getChat());
        return ajaxResult;
    }
}
